package com.boruan.shengtangfeng.admin.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.boruan.shengtangfeng.admin.jwt.UserSubject;
import com.boruan.shengtangfeng.admin.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.core.dto.ArticleCategoryDto;
import com.boruan.shengtangfeng.core.entity.Article;
import com.boruan.shengtangfeng.core.entity.ArticleCategory;
import com.boruan.shengtangfeng.core.entity.ArticleComment;
import com.boruan.shengtangfeng.core.entity.Log;
import com.boruan.shengtangfeng.core.entity.Article;
import com.boruan.shengtangfeng.core.entity.Log.OperateType;
import com.boruan.shengtangfeng.core.service.IArticleCommentService;
import com.boruan.shengtangfeng.core.service.IArticleService;
import com.boruan.shengtangfeng.core.service.ILogService;
import com.boruan.shengtangfeng.core.service.INoticeService;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.vo.ArticleCategoryVo;
import com.boruan.shengtangfeng.core.vo.ArticleCommentVo;
import com.boruan.shengtangfeng.core.vo.ArticleVo;
import com.boruan.shengtangfeng.core.vo.mapper.ArticleCategoryVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.ArticleCommentVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.ArticleVoMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@SuppressWarnings("all")
@RequestMapping("/admin/article")
@Api(value = "", tags = {"NO:7 文章相关接口"})
public class ArticleApi {
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IArticleCommentService articleCommentService;
    @Autowired
    private ILogService sysLogService;
    @Autowired
    private INoticeService noticeService;

    @GetMapping("/page")
    @ApiOperation(value = "NO:7-2 分页获取文章", notes = "")
    public GlobalReponse<PageQuery<ArticleVo>> page(@RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
													@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
													Article article) {
        PageQuery<Article> pageQuery = new PageQuery<Article>();
        pageQuery.setPageNumber(pageIndex);
        pageQuery.setPageSize(pageSize);
        article.setIsDeleted(false);
        articleService.pageQuery(pageQuery, article);
        List<Article> list = pageQuery.getList();
        List<ArticleVo> vos = ArticleVoMapper.MAPPER.toVo(list);
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }

    @PostMapping("addArticle")
    @ApiOperation(value = "NO:15-3 添加文章", notes = "")
    public GlobalReponse addArticle(@RequestBody Article dto) {

        articleService.addArticle(dto, JwtUtil.getCurrentJwtUser().getId());

        return GlobalReponse.success();
    }

    @GetMapping("updateArticle")
    @ApiOperation(value = "NO:15-3 发布，取消发布，推荐，取消推荐 删除文章", notes = "")
    public GlobalReponse updateArticle(@RequestParam String id, @RequestParam Integer type) {
        for (String s : id.split(",")) {
            long articleId = Long.parseLong(s);
            articleService.updateArticle(articleId, type, JwtUtil.getCurrentJwtUser().getId());
        }
        return GlobalReponse.success();
    }



    @GetMapping("/deleteComment")
    public GlobalReponse deleteComment(Long id) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();

        articleCommentService.deleteComment(id, userSubject.getId());

        return GlobalReponse.success();
    }

    @GetMapping("/getCategory")
    @ApiOperation(value = "NO:7-6 获取文章分类", notes = "")
    public GlobalReponse getCategory() {
        List<ArticleCategoryVo> list = articleService.getCategory();
        return GlobalReponse.success(list);
    }

//    @GetMapping("/listCategory")
//    @ApiOperation(value = "NO:7-7 获取所有文章分类", notes = "")
//    public GlobalReponse<List<ArticleCategoryVo>> listCategory(ArticleCategory articleCategory) {
//        List<ArticleCategory> list = articleService.getCategoryList(articleCategory);
//        return GlobalReponse.success(ArticleCategoryVoMapper.MAPPER.toVo(list));
//    }
    
    @GetMapping("pageCategory")
    @ApiOperation(value = "NO:7-7 获取文章分类", notes = "")
    public GlobalReponse<ArticleCategoryVo> pageCategory(ArticleCategoryDto articleCategoryDto,
                                                 @RequestParam(value = "pageIndex", defaultValue = "1") int

                                                         pageIndex,
                                                 @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {

        PageQuery<ArticleCategory> pageData = new PageQuery<ArticleCategory>();
        pageData.setPageNumber(pageIndex);
        pageData.setPageSize(pageSize);
        articleService.pageQueryCategory(pageData,articleCategoryDto);
        pageData.setList(ArticleCategoryVoMapper.MAPPER.toVo(pageData.getList()));
        return GlobalReponse.success(pageData);
    }
    @CrossOrigin
    @PostMapping(value = "/saveArticleCategory")
    @ApiOperation(value = "NO:7-8 添加文章分类", notes = "")
    public GlobalReponse saveArticleCategory(@RequestBody ArticleCategory articleCategory) {
        try {
            UserSubject userSubject = JwtUtil.getCurrentJwtUser();
            Log sysLog = new Log();
            if (articleCategory.getId() == null) {
                // 添加
                articleCategory.setCreateBy(userSubject.getName());
                articleCategory.setCreateTime(new Date());
                articleCategory.setIsDeleted(false);
                articleService.saveCategory(articleCategory);
                sysLog.setObjectId(articleCategory.getId());
                sysLog.setContent("管理员添加文章分类信息");
                sysLog.setOperateType(OperateType.ADD);
            } else {
                // 更新
                ArticleCategory old = articleService.getCategory(articleCategory.getId());
                old.setName(articleCategory.getName());
                old.setSort(articleCategory.getSort());
                old.setIsDefault(articleCategory.getIsDefault());
                old.setUpdateBy(userSubject.getName());
                old.setUpdateTime(new Date());
                articleService.saveCategory(old);
                sysLog.setObjectId(old.getId());
                sysLog.setContent("管理员修改文章分类信息");
                sysLog.setOperateType(OperateType.UPDATE);
            }
            sysLog.setCreateTime(new Date());
            sysLog.setOperater(userSubject.getId());
            sysLog.setLogType(Log.LogType.ADMIN);
            sysLogService.save(sysLog);
            return GlobalReponse.success();
        } catch (Exception e) {
            log.error("管理员编辑文章分类失败:{}", e);
            return GlobalReponse.fail();
        }
        
    }
    @GetMapping("deleteCategory")
    @ApiOperation(value = "NO:15-1 删除文章分类", notes = "")
    public GlobalReponse deleteCategory(Long id) {
        
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        ArticleCategory category = articleService.getCategory(id);
        category.setIsDeleted(true);
        category.setUpdateBy(userSubject.getId().toString());
        category.setUpdateTime(new Date());
        try {
            articleService.saveCategory(category);
            Log sysLog = new Log();
            sysLog.setContent("试题管理删除文章分类信息");
            sysLog.setCreateTime(new Date());
            sysLog.setOperater(userSubject.getId());
            sysLog.setObjectId(userSubject.getId());
            sysLog.setLogType(Log.LogType.ADMIN);
            sysLog.setOperateType(OperateType.DELETE);
            sysLogService.save(sysLog);
            return GlobalReponse.success();
        } catch (Exception e) {
            log.error("试题管理删除文章分类信息失败:{}", e.getMessage());
            return GlobalReponse.fail();
        }

    }
    @GetMapping(value = "/confirmArticle")
    @ApiOperation(value = "NO:23-5 审核文章", notes = "")
    public GlobalReponse confirmArticle(String id,Integer status,String remark) {
        for (String s : id.split(",")) {
            long articleId = Long.valueOf(s).longValue();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            UserSubject userSubject=JwtUtil.getCurrentJwtUser();
            Article article=articleService.findById(articleId);
            article.setStatus(status);
            article.setRemark(remark);
            articleService.save(article);
//            0 未审核 1 已审核 2 审核失败
            //用户上传的审核通过给用户发通知
            if(article.getUploadType()==1) {
                if(status==1) {
                    noticeService.addNotice(2, 1, articleId, article.getPublishId(), "内容审核通知","您于"+dateFormat.format(article.getCreateTime())+"发表过的文章"+"《"+article.getTitle()+"》，审核通过。");
                }else if(status==2){
                    if (remark!=null){
                        noticeService.addNotice(2, 1, articleId, article.getPublishId(), "内容审核通知","您于"+dateFormat.format(article.getCreateTime())+"发表过的文章"+"《"+article.getTitle()+"》，"+"因"+remark+"审核不通过。");
                    }else {
                        noticeService.addNotice(2, 1, articleId, article.getPublishId(), "内容审核通知","您于"+dateFormat.format(article.getCreateTime())+"发表过的文章"+"《"+article.getTitle()+"》，"+"因包含敏感内容审核不通过。");
                    }
                }
            }
            Log sysLog = new Log();
            sysLog.setObjectId(article.getId());
            sysLog.setContent("管理员审核文章信息："+status);
            sysLog.setOperateType(OperateType.UPDATE);
            sysLog.setCreateTime(new Date());
            sysLog.setOperater(userSubject.getId());
            sysLog.setLogType(Log.LogType.ADMIN);
            sysLogService.save(sysLog);
        }
        return GlobalReponse.success("审核成功");
    }
}
